/*
 * TwitterApi.java
 *
 * Copyright (C) 2005-2008 Tommi Laukkanen
 * http://www.substanceofcode.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.substanceofcode.twitter;

import com.substanceofcode.twitter.model.Status;
import com.substanceofcode.utils.HttpUtil;
import com.substanceofcode.utils.Log;
import com.substanceofcode.utils.StringUtil;
import java.io.IOException;
import java.util.Vector;

import com.sugree.twitter.TwitterMIDlet;
import com.sugree.twitter.JSONTwitterParser;
import com.sugree.twitter.TwitterException;

/**
 * TwitterApi
 *
 * @author Tommi Laukkanen (tlaukkanen at gmail dot com)
 */
public class TwitterApi {

	private String source;
    private String username;
    private String password;

    private static final String PUBLIC_TIMELINE_URL = "http://twitter.com/statuses/public_timeline.json";
    private static final String FRIENDS_TIMELINE_URL = "http://twitter.com/statuses/friends_timeline.json";
    private static final String USER_TIMELINE_URL = "http://twitter.com/statuses/user_timeline.json";
    private static final String REPLIES_TIMELINE_URL = "http://twitter.com/statuses/replies.json";
    private static final String STATUS_UPDATE_URL = "http://twitter.com/statuses/update.json";
	private static final String DIRECT_MESSAGES_URL = "http://twitter.com/direct_messages.json";

    /** Creates a new instance of TwitterApi */
    public TwitterApi(String source) {
		this.source = source;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Request public timeline from Twitter API.
     * @return Vector containing StatusEntry items.
     */
    public Vector requestPublicTimeline() throws TwitterException {
        return requestTimeline(PUBLIC_TIMELINE_URL, "");
    }    
    
    /**
     * Request public timeline from Twitter API.
     * @return Vector containing StatusEntry items.
     */
    public Vector requestFriendsTimeline(String since) throws TwitterException {
		if (since != null && since.length() > 0) {
			since = "since="+StringUtil.urlEncode(since);
		}
	    HttpUtil.setBasicAuthentication(username, password);
        return requestTimeline(FRIENDS_TIMELINE_URL, prepareParam(since));
    }    

    /**
     * Request public timeline from Twitter API.
     * @return Vector containing StatusEntry items.
     */
    public Vector requestUserTimeline() throws TwitterException {
	    HttpUtil.setBasicAuthentication(username, password);
        return requestTimeline(USER_TIMELINE_URL, prepareParam(""));
    }    

    /**
     * Request responses timeline from Twitter API.{
     * @return Vector containing StatusEntry items.
     */
    public Vector requestRepliesTimeline() throws TwitterException {
	    HttpUtil.setBasicAuthentication(username, password);
        return requestTimeline(REPLIES_TIMELINE_URL, prepareParam(""));
    }  
    
    /**
     * Request direct messages timeline from Twitter API.{
     * @return Vector containing StatusEntry items.
     */
    public Vector requestDirectMessagesTimeline() throws TwitterException {
        return requestTimeline(DIRECT_MESSAGES_URL, prepareParam(""));
    }  
    
    public Status updateStatus(String status) throws TwitterException {
		String response = "";
        try {
            String query = "status="+StringUtil.urlEncode(status);
            HttpUtil.setBasicAuthentication(username, password);
            response = HttpUtil.doPost(STATUS_UPDATE_URL, prepareParam(query));
        } catch(Exception ex) {
			ex.printStackTrace();
            Log.error("Error while updating status: " + ex.getMessage());
			throw new TwitterException("update "+ex.toString());
        }
		return null;
        //return JSONTwitterParser.parseStatus(response);
    }
    
    private Vector requestTimeline(String timelineUrl, String param) throws TwitterException {
        Vector entries = new Vector();
        try {
            String response = HttpUtil.doGet(timelineUrl, param);
			if (response.length() > 0) {
	            entries = JSONTwitterParser.parseStatuses(response);
			}
        } catch (IOException ex) {
            ex.printStackTrace();
			throw new TwitterException("request "+ex);
        } catch (Exception ex) {
            ex.printStackTrace();
			throw new TwitterException("request "+ex);
        }
        return entries;        
    }
    
    private String prepareParam(String param) {
		String newParam = "";
		if (param.length() > 0) {
			newParam = param+"&source="+source;
		} else {
			newParam = "source="+source;
		}
		return newParam;
	}
    
}
